#!/usr/bin/env python3
"""
配置管理模块
用于管理环境变量和配置项
"""

import os
import logging
from dotenv import load_dotenv

# 加载 .env 文件
load_dotenv()

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

class Config:
    """配置管理类"""
    
    # 数据库配置
    DB_TYPE = os.getenv('ZABBIX_DB_TYPE', 'postgresql').lower()
    DB_HOST = os.getenv('ZABBIX_DB_HOST', 'localhost')
    DB_USER = os.getenv('ZABBIX_DB_USER', 'zabbix')
    DB_PASSWORD = os.getenv('ZABBIX_DB_PASSWORD', '')
    DB_NAME = os.getenv('ZABBIX_DB_NAME', 'zabbix')
    
    # 根据数据库类型设置默认端口
    DB_PORT = int(os.getenv('ZABBIX_DB_PORT', 
                           '5432' if DB_TYPE == 'postgresql' else '3306'))
    
    # AI引擎配置
    AI_ENGINE = os.getenv('AI_ENGINE', 'deepseek').lower()
    ENABLE_AI_ANALYSIS = os.getenv('ENABLE_AI_ANALYSIS', 'true').lower() == 'true'
    
    # DeepSeek API配置
    DEEPSEEK_API_KEY = os.getenv('DEEPSEEK_API_KEY')
    DEEPSEEK_API_URL = os.getenv('DEEPSEEK_API_URL', 'https://api.deepseek.com/v1/chat/completions')
    DEEPSEEK_MODEL = os.getenv('DEEPSEEK_MODEL', 'deepseek-chat')
    DEEPSEEK_TIMEOUT = int(os.getenv('DEEPSEEK_TIMEOUT', '30'))
    
    # Ollama配置
    OLLAMA_BASE_URL = os.getenv('OLLAMA_BASE_URL', 'http://localhost:11434')
    OLLAMA_MODEL = os.getenv('OLLAMA_MODEL', 'llama3.1:8b')
    OLLAMA_TIMEOUT = int(os.getenv('OLLAMA_TIMEOUT', '60'))
    
    # 飞书Webhook配置
    LARK_WEBHOOK_URL = os.getenv('LARK_WEBHOOK_URL')
    
    @classmethod
    def validate(cls) -> bool:
        """验证必要配置项"""
        if not cls.LARK_WEBHOOK_URL:
            logging.error("请配置 LARK_WEBHOOK_URL 环境变量")
            return False
        
        if cls.DB_TYPE not in ['postgresql', 'mysql']:
            logging.error(f"不支持的数据库类型: {cls.DB_TYPE}。支持的类型: postgresql, mysql")
            return False
        
        # 验证AI引擎配置
        if cls.AI_ENGINE not in ['deepseek', 'ollama']:
            logging.error(f"AI引擎配置无效: {cls.AI_ENGINE} (仅支持 deepseek 或 ollama)")
            return False
        
        # 验证选择的AI引擎配置
        if cls.ENABLE_AI_ANALYSIS:
            if cls.AI_ENGINE == 'deepseek' and not cls.DEEPSEEK_API_KEY:
                logging.warning("未配置DeepSeek API密钥，将使用内置分析")
            elif cls.AI_ENGINE == 'ollama' and not cls.OLLAMA_BASE_URL:
                logging.warning("未配置Ollama服务地址，将使用内置分析")
            
        logging.info(f"配置验证通过，当前AI引擎: {cls.AI_ENGINE}")
        return True
    
    @classmethod
    def get_db_config(cls) -> dict:
        """获取数据库配置"""
        return {
            'type': cls.DB_TYPE,
            'host': cls.DB_HOST,
            'port': cls.DB_PORT,
            'user': cls.DB_USER,
            'password': cls.DB_PASSWORD,
            'database': cls.DB_NAME
        }
    
    @classmethod
    def get_api_config(cls) -> dict:
        """获取API配置"""
        return {
            'ai_engine': cls.AI_ENGINE,
            'enable_ai_analysis': cls.ENABLE_AI_ANALYSIS,
            'deepseek': {
                'api_key': cls.DEEPSEEK_API_KEY,
                'api_url': cls.DEEPSEEK_API_URL,
                'model': cls.DEEPSEEK_MODEL,
                'timeout': cls.DEEPSEEK_TIMEOUT,
                'enabled': cls.AI_ENGINE == 'deepseek'
            },
            'ollama': {
                'base_url': cls.OLLAMA_BASE_URL,
                'model': cls.OLLAMA_MODEL,
                'timeout': cls.OLLAMA_TIMEOUT,
                'enabled': cls.AI_ENGINE == 'ollama'
            },
            'lark_webhook': cls.LARK_WEBHOOK_URL
        }